package com.medical.admin.patient.service.Impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.medical.admin.patient.common.dto.PatientDto;
import com.medical.admin.patient.entity.Patient;
import com.medical.admin.patient.ex.PatientException;
import com.medical.admin.patient.mapper.PatientMapper;
import com.medical.admin.patient.service.PatientService;
import com.qf.medical.ex.ServiceException;
import com.qf.medical.response.ResponseCode;
import com.qf.medical.utils.BeanConvertUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

@Service
public class PatientServiceImpl implements PatientService {
    @Resource
    private PatientMapper patientMapper;

    @Override
    public PatientDto researchPatient(Long patientId) {
        Patient patient = patientMapper.selectById(patientId);
        if (ObjectUtils.isEmpty(patient)){
            throw new PatientException(ResponseCode.PATIENT_NULL_ERROR);
        }
        return BeanConvertUtils.convertTo(patient,PatientDto::new);
    }

    @Override
    public Integer addPatient(PatientDto patientDto) {
        //判断身份证号码和电话号码是否存在，存在说明账号已存在
        Patient patient = patientMapper.select(BeanConvertUtils.convertTo(patientDto, Patient::new));
        if (!ObjectUtils.isEmpty(patient)){
            throw new ServiceException(ResponseCode.PATIENT_IS_HAVE);
        }
        //添加到数据库
        int count = patientMapper.insert(BeanConvertUtils.convertTo(patientDto,Patient::new));
        if (count <= 0 ){
            throw new PatientException(ResponseCode.PATIENT_ADD_ERROR);
        }
        return count;
    }

    @Override
    public Integer modifyPatient(PatientDto patientDto) {
        int count = patientMapper.updateByPatientId(BeanConvertUtils.convertTo(patientDto,Patient::new));
        if (count <= 0 ){
            throw new PatientException(ResponseCode.PATIENT_UPDATE_ERROR);
        }
        return count;
    }

    @Override
    public Integer deletePatient(long patientId) {
        int count = patientMapper.deleteById(patientId);
        if (count <= 0 ){
            throw new PatientException(ResponseCode.PATIENT_DELETE_ERROR);
        }
        return count;
    }

    @Override
    public IPage<PatientDto> findAllPatient(Integer page, Integer size) {
        Page<Patient> objectPage = new Page<>(page, size);
        IPage<Patient> iPage = patientMapper.selectPatientList(objectPage);
        if (ObjectUtils.isEmpty(iPage)){
            throw new PatientException(ResponseCode.PATIENT_NULL_ERROR);
        }
        return iPage.convert(patient -> BeanConvertUtils.convertTo(patient,PatientDto::new));
    }
}
